package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import model.Instrument;
import model.Piece;
import model.Sequence;
import view.EditorPanel;
import view.GUI;
import view.tool.ToolType;

/**
 * A SequenceChangeListener is responsible for changing properties of a Sequence
 * and if needed, removing it from the Piece.<br>
 * This is mainly used along side SequenceTool to apply changes made in it to
 * the model.
 */
public class SequenceChangeListener implements ActionListener, ChangeListener {

	//ActionCommands this listener can handle
	public static final String DELETE_SEQUENCE = "DELETE_SEQUENCE", VOLUME = "VOLUME";

	private Sequence sequence;
	private Piece piece;
	private GUI gui;

	public SequenceChangeListener(Piece piece, Sequence sequence, GUI gui) {
		this.piece = piece;
		this.sequence = sequence;
		this.gui = gui;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String command = e.getActionCommand();

		int index = piece.getSequences().indexOf(sequence);
		EditorPanel editorPanel = gui.getEditorPanel();
		if(command.equals(DELETE_SEQUENCE)) {
			//Delete the Sequence
			editorPanel.hideSelectedTrackPanel();
			piece.removeSequence(index);
			editorPanel.removeSequence(index);
			gui.setToolPanel(ToolType.EFFECTS);
		} else {
			//Change the Instrument
			Instrument newInstrument = Instrument.valueOf(command);
			sequence.setInstrument(newInstrument);
			editorPanel.changeInstrument(index, newInstrument);
		}
	}

	@Override
	public void stateChanged(ChangeEvent e) {
		Object obj = e.getSource();

		if(obj instanceof JSlider) {
			//Assume it's a volume slider.
			JSlider slider = (JSlider)obj;
			String name = slider.getName();
			int value = slider.getValue();
			if(name.equals(VOLUME)) {
				sequence.setVolume(value);
			}
		}
	}


}
